# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: donggu

from statistics import stdev
import math


def sharpe(pnls, eps=1e-6):
  if len(pnls) < 2:
    return 0.0
  mean = sum(pnls) / len(pnls)
  return mean / (stdev(pnls) + eps)


def sortino(pnls, target=0, eps=1e-6):
  if len(pnls) < 2:
    return 0.0

  downside = 0.0
  for pnl in pnls:
    downside += min(target, pnl - target)**2

  tdd = (downside / len(pnls))**0.5
  mean = sum(pnls) / len(pnls)
  return (mean - target) / (tdd + eps)


def profit_factor(pnls, eps=1e-6):
  if len(pnls) < 2:
    return 0.0

  profit = 0.0
  loss = 0.0
  for pnl in pnls:
    if pnl > 0:
      profit += pnl
    else:
      loss += -pnl
  return profit / (loss + eps)


def logistic(x):
  return 0.5 + 0.5 * math.tanh(x / 2)


def donggu1(a):
  if len(a) < 2:
    return 0.0
  s = 0
  r = 0.05
  for i in a:
    if i > 0:
      s += i**(1 - r)
    else:
      s += -(-i)**(1 + r)
  return s


def donggu2(a):
  if len(a) < 2:
    return 0.0
  s = 0
  mean = sum(a) / len(a)
  sd = stdev(a)
  if sd == 0:
    return sum(a)
  for i in a:
    pos = (i - mean) / (sd * 5)
    s += logistic(-pos) * 2 * i
  return s
